package com.shuyun.concurrent;

/**
 * @description:
 * @author: shuai.chen@shuyun.com
 * @date: 2023/1/11 5:02 PM
 */
public class VolatileTest implements Runnable {
    private volatile boolean flag = false;
    @Override
    public void run() {
        while (!flag){

        }
        System.out.println("线程结束运行...");
    }
    public void setFlag(boolean flag) {
        this.flag = flag;
    }
    public static void main(String[] args) throws InterruptedException {
        // 启动了 main 线程

        VolatileTest v = new VolatileTest();
        Thread t1 = new Thread(v);
        // 启动了t1线程
        t1.start();

        // main线程休眠2秒
        Thread.sleep(2000);

        //在main线程修改flag, t1线程能感知到吗
        v.setFlag(true);

        // 测试发现: 如果volatile修饰flag, t1线程可以结束, 不修饰的话, t1不结束.
    }
}
